/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mycompany.delivery.tableModels;

import com.mycompany.delivery.dto.ContactDTO;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

/**
 *
 * @author Katarína Hrabovská <katarina.hrabovska1992@gmail.com>
 */
public class DeliveryContactTableModel extends AbstractTableModel {
    private String stringTable;
    private List<ContactDTO> contacts;
    RestTemplate restTemplate = new RestTemplate();
    //private java.util.ResourceBundle bundle;
 
    public DeliveryContactTableModel(String stringTable) {
        this.stringTable = stringTable;
       contacts = new ArrayList<ContactDTO>(); 
     //   bundle = java.util.ResourceBundle.getBundle("Locales/localization");
    }
    
    @Override
    public int getRowCount() {
        return contacts.size();
    }
 
    
    @Override
    public int getColumnCount() {
        return 1;
    }
 
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        ContactDTO contact = contacts.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return contact.getName()+" "+contact.getSurname();
            default:
                throw new IllegalArgumentException("error with column index");
        }
    }
    
    public ContactDTO getContactAt(int index){
        return contacts.get(index);
    }
    
    public void initContacts() {
           try {
            ContactDTO[] contactsArray = restTemplate.getForObject("http://localhost:8080/pa165/contacts/getAllContactJson", ContactDTO[].class);
            contacts.clear();
            contacts.addAll(Arrays.asList(contactsArray));
        } catch (HttpClientErrorException e) {
            System.err.println(e.getMessage());
            }
               catch (ResourceAccessException ex)
         {
          //NEJDE WEB, JIŽ OZNÁMENO
             
         }   
    }
    
    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case 0:
                return String.class;
            default:
                throw new IllegalArgumentException("error with column class");
        }
    }
    
    @Override
    public String getColumnName(int columnIndex) {
        switch (columnIndex) {
            case 0:
                return stringTable;
            default:
                throw new IllegalArgumentException("error with column name");
        }
    }
    
}
